////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2012 www.iflytek.com. All Rights Reserved.
//  This software for customer relationship management system, developed by Iflytek_ZY team.
//  Software code and design for the team, copy rights reserved.
////////////////////////////////////////////////////////////////////////////////

package com.iflytek.ci.main.controller;

import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.iflytek.ci.common.service.AttachmentService;
import com.iflytek.ci.qams.domain.Priopity;
import com.iflytek.ci.qams.service.PriopityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 公共请求服务接口.
 * </p>
 *
 * @author poplar.yfyang
 * @version 1.0 2012-11-05 9:17 AM
 * @since JDK 1.5
 */
@Controller
@RequestMapping("action/")
public class CommonController extends BaseController {
    /**
     * 序列化ID
     */
    private static final long serialVersionUID = 2163183853365996087L;
    /**
     * 文件服务
     */
    @Autowired
    private AttachmentService attachmentService;
    /**
     * 可上传的文件格式
     */
    @Value("${allow_image_types}")
    private String allowedTypes;
    /**
     * 集成反馈系统存放的地址
     */
    @Value("${tools_path}")
    private String tools_path;
    /**
     * 优先级服务
     */
    @Autowired
    private PriopityService priopityService;

    /**
     * 获取系统所有的优先级信息
     *
     * @return 优先级信息
     */
    @RequestMapping(value = "pripitys", method = RequestMethod.GET)
    @ResponseBody
    public List<Priopity> priopitys() {
        return priopityService.priopity();
    }

    /**
     * 文件上传
     * </p>
     * fixed:Image upload can not be displayed when viewed.
     *
     * @return 文件上传操作
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upload(@RequestParam(value = "imgFile") MultipartFile image,
                                      HttpServletRequest request) {
        final Map<String, Object> kindeditor_msg = Maps.newHashMap();
        if (!image.isEmpty()) {
            if (validateImage(image)) {
                String name = UUID.randomUUID().toString();
                try {
                    attachmentService.add_attachment(name, image.getBytes());
                } catch (IOException e) {
                    kindeditor_msg.put("error", 1);
                    kindeditor_msg.put("message", "文件上传失败");
                    return kindeditor_msg;
                }
                kindeditor_msg.put("error", 0);
                String context_path = request.getContextPath();
                kindeditor_msg.put("url", context_path + "/action/attach/" + name);
            } else {
                kindeditor_msg.put("error", 1);
                kindeditor_msg.put("message", "文件格式不是图片");
            }
        }
        return kindeditor_msg;
    }

    /**
     * 获取文件，并将文件信息输出到response流
     *
     * @param name     文件名称
     * @param response 响应流
     */
    @RequestMapping(value = "attach/{name}")
    public void image(@PathVariable String name, HttpServletResponse response) {
        try {
            attachmentService.attachment_write_to_output(response.getOutputStream(), name);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取项目的Tools的JS文件，并将文件信息输出到response流
     *
     * @param name     文件名称
     * @param response 响应流
     */
    @RequestMapping(value = "tools/{name}.js")
    public void tools(@PathVariable String name, HttpServletResponse response) {
        PrintWriter writer = null;
        try {
            File tools_file = new File(tools_path + name + ".js");
            if (tools_file.exists()) {
                Files.copy(tools_file, response.getOutputStream());
            } else {
                writer = response.getWriter();
                writer.append("<script>alert('无法找到指定项目的集成反馈工具')</script>");
            }
        } catch (IOException e) {
            try {
                writer = response.getWriter();
                writer.append("<script>alert('IO错误')</script>");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 检验是否为图片信息
     *
     * @param image 上传的文件
     * @return true 是图片
     */
    private boolean validateImage(MultipartFile image) {
        String contextType = image.getContentType();
        return allowedTypes.contains(contextType);
    }
}
